<template>
  <div>
    <div class="flex justify-between items-center mb-[8px]">
      <el-button type="primary" @click="visible = true">
        +添加申报规则
      </el-button>
      <div class="flex items-center text-[12px] text-[#999] leading-[17px]">
         <svg-icon
        icon-class="hint_line"
        class="mr-[2px] text-[16px] align-middle"
      />
        <span>
          按照国家不同申报规则可添加多条，如所有国家都申报规则一致，则只需维护一种且目的国家为全部即可！
        </span>
      </div>
    </div>
    <vxe-grid ref="tableRef" v-bind="tableOptions" />
    <RuleDialog
      :value="selectItem"
      v-model="visible"
      :optionsData="optionsData"
      :useReq="!!id"
      :declare_rules_id="id"
      @add="handleAddRule"
      @edit="handleEditRule"
      @close="selectItem = {}"
      @refresh="handleRefresh"
    />
  </div>
</template>
<script setup lang="jsx">
import { ElMessage } from 'element-plus'

import RuleDialog from '../RuleDialog/index.vue'

import { deleteDetail } from '../../api'

const emit = defineEmits(['refresh'])

const props = defineProps({
  optionsData: { type: Object, default: () => ({}) },
  data: { type: Array, default: () => [] },
  id: { type: String, default: '' },
})
const visible = ref()
const tableRef = ref()
const selectItem = ref()

const findLabel = (field, val) => {
  if (!val) return ''
  return props.optionsData?.[field].find(n => n.value === val)?.label
}

const renderCountry = val => {
  if (!val) return ''
  const arr =
    props.optionsData['mapCountry']?.filter(n => val.includes(n.country)) || []
  return arr.length ? arr.map(n => n.country_name).join() : ''
}

watch(
  () => props.data,
  val => {
    if (!val?.length) return
    tableRef?.value.reloadData(val)
  }
)

const tableOptions = {
  pagerConfig: { pageSize: 20 },
  round: true,
  height: '400px',
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  rowConfig:{
    height:100
  },
  columns: [
    { fixed: 'left', width: 50, title: '序号', field: 'id' },
    {
      fixed: 'left',
      title: '目的国家',
      minWidth: 120,
      field: 'destination_country',
      slots: {
        default: ({ row }) => renderCountry(row.destination_country),
      },
    },
    {
      title: '申报重量方式',
      width: 200,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.weight_calc !== undefined && (
                <div>
                  {row.weight_calc === 0 ? (
                    <div>
                      <span>固定重量：</span>
                      {row.fixed_weight}kg
                    </div>
                  ) : (
                    <div>
                      <div>{findLabel('weight_type', row.weight_type)}</div>
                      {row.min_weight !== undefined && (
                        <div>最低: {row.min_weight}kg</div>
                      )}
                      {row.max_weight !== undefined && (
                        <div>最低: {row.max_weight}kg</div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )
        },
      },
    },
    {
      title: '申报价值方式',
      width: 200,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.price_calc !== undefined && (
                <div>
                  {row?.price_calc === 0 ? (
                    <div>
                      <span>固定价格：</span>
                      {row.fixed_price}
                    </div>
                  ) : (
                    <div>
                      <div>{findLabel('price_type', row.price_type)}</div>
                      {row.price_percent !== undefined && (
                        <div>比率：{row.price_percent}%</div>
                      )}
                      {row.min_price !== undefined && (
                        <div>最低: {row.min_price}kg</div>
                      )}
                      {row.max_price !== undefined && (
                        <div>最低: {row.max_price}kg</div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )
        },
      },
    },
    { title: '申报币种', width: 140, field: 'currency' },
    {
      title: '申报链接',
      width: 170,
      field: 'declare_link_type',
      slots: {
        default: ({ row }) => (
          <div>{findLabel('declare_link_type', row.declare_link_type)}</div>
        ),
      },
    },
    { title: '税率%', width: 160, field: 'tax_rate' },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: {
        default: ({ row, rowIndex }) => {
          return (
            <div>
              <el-button link type='primary' onClick={() => handleEdit(row)}>
                编辑
              </el-button>
              <el-button link type='danger' onClick={() => handleDelete(row)}>
                删除
              </el-button>
            </div>
          )
        },
      },
    },
  ],
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: 'data',
      total: 'total',
    },
    ajax: {
      query: ({ page }) => {},
    },
  },
}

const getTableData = () => {
  return tableRef.value.getTableData().tableData
}

const handleAddRule = item => {
  tableRef.value.insert(item)
}

const handleEdit = item => {
  selectItem.value = JSON.parse(
    JSON.stringify({
      ...item,
      weightCalc: { ...item },
      priceCalc: { ...item },
    })
  )
  visible.value = true
}

const handleDelete = async row => {
  if (!row.id) {
    tableRef.value.remove(row)
    return
  }
  try {
    const { code, message } = await deleteDetail({ id: row.id })
    if (code === 200) {
      tableRef.value.remove(row)
    } else {
      ElMessage.warning(message)
    }
  } catch (e) {
    console.error(e)
  }
}

const remove = () => {
  tableRef.value.remove()
}

const handleEditRule = item => {
  const _data = getTableData()
  const newData = _data.map(n => (n._X_ROW_KEY === item._X_ROW_KEY ? item : n))
  tableRef.value.reloadData(newData)
}

const handleRefresh = () => {
  emit('refresh')
}

defineExpose({ getTableData, remove })
</script>
